package com.example.hxds.odr.config;


import com.example.hxds.odr.db.dao.OrderBillDao;
import com.example.hxds.odr.db.dao.OrderDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Objects;

@Component
@Slf4j
public class KeyExpiredListener extends KeyExpirationEventMessageListener {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private OrderBillDao orderBillDao;

    public KeyExpiredListener(RedisMessageListenerContainer redisMessageListenerContainer) {
        super(redisMessageListenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {

        //从消息队列中接收消息
        if ("__keyevent@5__:expired".equals(new String(message.getChannel()))){
            //反序列化Key，否则出现乱码
            String key = Objects.requireNonNull(new JdkSerializationRedisSerializer().deserialize(message.getBody())).toString();
            if (key.contains("order#")){
                Long orderId = Long.valueOf(key.split("#")[1]);
                HashMap<String, Long> param = new HashMap<>() {{
                    put("orderId", orderId);
                }};
                int rows = orderDao.deleteUnAcceptOrder(param);
                if (rows==1){
                    log.info("删除了无人接单的订单：" + orderId);
                }
                rows = orderBillDao.deleteUnAcceptOrderBill(orderId);
                if (rows == 1) {
                    log.info("删除了无人接单的账单：" + orderId);
                }
            }
            super.onMessage(message,pattern);
        }
    }
}
